package com.member.web.controller.shop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.domain.R;
import com.member.common.core.domain.model.LoginUser;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.*;
import com.member.common.utils.DateUtils;
import com.member.common.utils.SecurityUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.TokenUtils;
import com.member.common.utils.http.HttpUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.*;
import com.member.shop.dto.ExternalAddressDto;
import com.member.shop.dto.ExternalCouponDto;
import com.member.shop.dto.ExternalUserDto;
import com.member.shop.dto.SubordinateDto;
import com.member.shop.mapper.SysBizShopCertificationMapper;
import com.member.shop.service.ISysBizOrderService;
import com.member.shop.service.ISysBizShopCertificationService;
import com.member.shop.service.ISysBizUserAddressService;
import com.member.shop.service.ISysBizUserService;
import com.member.shop.vo.SysBizUserExportVo;
import com.member.shop.vo.SysBizUserTreeVo;
import com.member.shop.vo.SysBizUserVo;
import com.member.shop.vo.UpLowerLevelExportVo;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 【用户列表】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-01-03
 **/
@RestController
@RequestMapping("/shop/user")
public class SysBizUserController extends BaseController {
    @Resource
    private ISysBizUserService sysBizUserService;


    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;


    @Value("${coupon.userAddress}")
    private String userAddressUrl;

    @Resource
    private ISysBizUserAddressService sysBizUserAddressService;
    /**
     * 查询用户列列表
     */
    @PreAuthorize("@ss.hasPermi('shop:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizUser sysBizUser) {
        startPage();
        setTenantId(sysBizUser);
        List<SysBizUserVo> list = sysBizUserService.selectSysBizUserListAll(sysBizUser);
        return getDataTable(list);
    }


    /**
     * 查询专属经理列表
     */
    @PreAuthorize("@ss.hasPermi('shop:user:list')")
    @GetMapping("/listUserSales")
    public TableDataInfo listUserSales(SysBizUser sysBizUser) {
        startPage();
        setTenantId(sysBizUser);
        List<SysBizUser> list = sysBizUserService.listUserSales(sysBizUser);
        return getDataTable(list);
    }






    private void setTenantId(SysBizUser sysBizUser) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizUser.setTenantId(tenantId);
        }
    }
    /**
     * 查询用户列列表(上下级关系树)
     */
    @PreAuthorize("@ss.hasPermi('shop:user:list')")
    @GetMapping("/upLowerLevel")
    public AjaxResult upLowerLevel(SysBizUser sysBizUser) {
        SysBizUserTreeVo sysBizUserTreeVo = sysBizUserService.upLowerLevel(sysBizUser);
        return success(sysBizUserTreeVo);
    }

    /**
     * 导出用户列列表
     */
    @Log(title = "用户列", businessType = BusinessType.EXPORT)
    @PostMapping("/exportUpLowerLevel")
    public void exportUpLowerLevel(HttpServletResponse response, SysBizUser sysBizUser) {
        List<UpLowerLevelExportVo> list = sysBizUserService.selectUpLowerLevelExport();
        ExcelUtil<UpLowerLevelExportVo> util = new ExcelUtil<UpLowerLevelExportVo>(UpLowerLevelExportVo.class);
        util.exportExcel(response, list, "上下级列表");
    }

    /**
     * 查询用户列列表
     */
    @PreAuthorize("@ss.hasPermi('shop:user:listChild')")
    @GetMapping("/listChild")
    public TableDataInfo listChild(SysBizUser sysBizUser) {
        startPage();
        List<SysBizUserVo> list = sysBizUserService.listChild(sysBizUser);
        return getDataTable(list);
    }

    /**
     * 导出用户列列表
     */
    @PreAuthorize("@ss.hasPermi('shop:user:export')")
    @Log(title = "用户列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizUser sysBizUser) {
        setTenantId(sysBizUser);
        List<SysBizUserExportVo> list = sysBizUserService.selectSysBizUserListExportAll(sysBizUser);
        ExcelUtil<SysBizUserExportVo> util = new ExcelUtil<SysBizUserExportVo>(SysBizUserExportVo.class);
        util.exportExcel(response, list, "用户列数据");
    }

    /**
     * 获取用户列详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysBizUserService.selectSysBizUserById(id));
    }

    @Value("${idCard.appCode}")
    private String appCode;

    @Value("${idCard.url}")
    private String url;

    /**
     * 新增用户列
     */
    @PreAuthorize("@ss.hasPermi('shop:user:add')")
    @Log(title = "用户列", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizUser sysBizUser) throws IOException {
        if (StringUtils.isNotBlank(sysBizUser.getMemberPhone())) {
            sysBizUser.setUserPhone(sysBizUser.getMemberPhone());
        }
        if (sysBizUserService.hasUserPhone(sysBizUser.getUserPhone())) {
            return warn("该手机号已存在");
        }
//        if (StringUtils.isNotBlank(sysBizUser.getFullName()) && StringUtils.isNotBlank(sysBizUser.getIdCard())) {
//            // 实名验证start
//            Map<String, String> params = new HashMap<>();
//            params.put("idcard", sysBizUser.getIdCard());
//            params.put("name", sysBizUser.getFullName());
//            String result = postForm(appCode, url, params);
//            JSONObject resultData = JSON.parseObject(result);
//            if (!"0".equals(resultData.get("code"))) {
//                return warn(resultData.get("message").toString());
//            }
//            JSONObject jsonObject = JSON.parseObject(resultData.get("result").toString());
//            if ("2".equals(jsonObject.get("res").toString())) {
//                return warn("姓名与身份证号不一致");
//            }
//            if (!"1".equals(jsonObject.get("res").toString())) {
//                return warn(jsonObject.get("description").toString());
//            }
//            List<SysBizUser> users = sysBizUserService.list(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getIdCard,
//                    sysBizUser.getIdCard()));
//            if (!CollectionUtils.isEmpty(users)) {
//                return warn("身份证号码已存在");
//            }
//            // 实名验证end
//        }
        sysBizUser.setUserRole(StandingEnum.IS_MEMBER.getKey());
        sysBizUser.setIsRegisterMember(1);
        sysBizUser.setProcessStatus(2);
        sysBizUser.setProcessTime(DateUtils.getNowDate());
        sysBizUser.setVerifyStatus(1);
        sysBizUser.setVerifyTime(DateUtils.getNowDate());
        return toAjax(sysBizUserService.insertSysBizUser(sysBizUser));
    }

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        for (String key : params.keySet()) {
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 修改用户列
     */
//    @PreAuthorize("@ss.hasAnyPermissions('shop:user:edit,shop:user:setMember,shop:user:lookMember,shop:user:setMemberGrade,shop:user:recharge,shop:user:displayedUpdate,shop:user:setMemberGrade')")
    @Log(title = "用户列", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizUser sysBizUser) throws IOException {
        return toAjax(sysBizUserService.updateSysBizUser(sysBizUser));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasAnyPermissions('shop:user:delete')")
    @Log(title = "用户列", businessType = BusinessType.DELETE)
    @PostMapping("/deleteUser/{id}")
    public AjaxResult deleteUser(@PathVariable Long id) {
//        List<SysBizUser> list = sysBizUserService.list(
//                new LambdaQueryWrapper<SysBizUser>()
//                        .eq(SysBizUser::getParentId, id)
//                        .eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey())
//        );
//        if (!CollectionUtils.isEmpty(list)) {
//            return warn("该用户存在下级用户,不能删除");
//        }
        SysBizUser bizUser = sysBizUserService.getById(id);

        sysBizShopCertificationService.update(
                new LambdaUpdateWrapper<SysBizShopCertification>()
                        .eq(SysBizShopCertification::getUserId, id)
                        .set(SysBizShopCertification::getDeleted, OrderDeleteEnum.DELETE.getKey())
        );

        if(bizUser.getIsSale()==1){
            sysBizShopCertificationService.update(
                    new LambdaUpdateWrapper<SysBizShopCertification>()
                            .eq(SysBizShopCertification::getSalesUserId, bizUser.getId())
                            .set(SysBizShopCertification::getSalesUserId, null)
            );
        }

        sysBizUserService.update(
                new LambdaUpdateWrapper<SysBizUser>()
                        .eq(SysBizUser::getId, id)
                        .set(SysBizUser::getDeleted, OrderDeleteEnum.DELETE.getKey())
                        .set(SysBizUser::getUserPhone,bizUser.getUserPhone()+"_0")
        );


        sysBizOrderService.update(
                new LambdaUpdateWrapper<SysBizOrder>()
                        .eq(SysBizOrder::getUserId, id)
                        .set(SysBizOrder::getDelStatus, OrderDeleteEnum.DELETE.getKey())
        );

        return toAjax(sysBizUserService.update(
                new LambdaUpdateWrapper<SysBizUser>()
                        .eq(SysBizUser::getId, id)
                        .set(SysBizUser::getDeleted, OrderDeleteEnum.DELETE.getKey())
                        .set(SysBizUser::getUserPhone,bizUser.getUserPhone()+"_0")
        ));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasAnyPermissions('shop:user:edit')")
    @Log(title = "用户列", businessType = BusinessType.UPDATE)
    @PostMapping("/resetUserPwd/{id}")
    public AjaxResult resetUserPwd(@PathVariable Long id) {
        SysBizUser sysBizUser = sysBizUserService.getById(id);
        return toAjax(sysBizUserService.update(
                new LambdaUpdateWrapper<SysBizUser>()
                        .eq(SysBizUser::getId, id)
                        .set(SysBizUser::getPassword, SecurityUtils.encryptPassword(sysBizUser.getUserPhone()))
        ));
    }

    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasAnyPermissions('shop:user:edit')")
    @Log(title = "用户列", businessType = BusinessType.UPDATE)
    @PostMapping("/editUser")
    public AjaxResult editUser(@RequestBody SysBizUser sysBizUser) {
        return toAjax(sysBizUserService.update(
                new LambdaUpdateWrapper<SysBizUser>()
                        .eq(SysBizUser::getId, sysBizUser.getId())
                        .set(SysBizUser::getFullName, sysBizUser.getFullName())
                        .set(SysBizUser::getUserPhone, sysBizUser.getUserPhone())
        ));
    }

    /**
     * 修改用户列
     */
    @PreAuthorize("@ss.hasPermi('shop:user:displayedUpdate')")
    @Log(title = "修改用户列", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/surplusPUT")
    public AjaxResult surplusPUT(@RequestBody SysBizUser sysBizUser) {
        setTenantId(sysBizUser);
        return toAjax(sysBizUserService.surplusPUT(sysBizUser));
    }

    /**
     * 修改用户列
     */
    @PreAuthorize("@ss.hasPermi('shop:user:displayedUpdate')")
    @Log(title = "充值可发展会员数", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/availableMembersPUT")
    public AjaxResult availableMembersPUT(@RequestBody SysBizUser sysBizUser) {
        return toAjax(sysBizUserService.updateById(sysBizUser));
    }

    /**
     * 禁用启用
     */
    @PreAuthorize("@ss.hasAnyPermissions('shop:user:edit,shop:user:setMember,shop:user:lookMember,shop:user:setMemberGrade,shop:user:recharge,shop:user:displayedUpdate,shop:user:setMemberGrade')")
    @Log(title = "用户列", businessType = BusinessType.UPDATE)
    @PutMapping("/updateUserStatus")
    public AjaxResult updateUserStatus(@RequestBody SysBizUser sysBizUser) {
        return toAjax(sysBizUserService.updateById(sysBizUser));
    }


    @PreAuthorize("@ss.hasAnyPermissions('shop:user:edit,shop:user:setMember,shop:user:lookMember,shop:user:setMemberGrade,shop:user:recharge,shop:user:displayedUpdate,shop:user:setMemberGrade')")
    @Log(title = "用户列", businessType = BusinessType.UPDATE)
    @PutMapping("/updateSales")
    public AjaxResult updateSales(@RequestBody SysBizUser sysBizUser) {

        //如果改成销售 要删除店铺认证
//        if(sysBizUser.getIsSale()==1){
//            sysBizShopCertificationService.update(
//                    new LambdaUpdateWrapper<SysBizShopCertification>()
//                            .eq(SysBizShopCertification::getUserId, sysBizUser.getId())
//                            .set(SysBizShopCertification::getDeleted, 1)
//            );
//        }else{
//            sysBizUser.setTenantId(null);
//        }
        //
        if(sysBizUser.getIsSale()==1) {
            SysBizShopCertification sysBizShopCertifications = sysBizShopCertificationService.getOne(
                    new LambdaQueryWrapper<SysBizShopCertification>()
                            .eq(SysBizShopCertification::getUserId, sysBizUser.getId())
                            .eq(SysBizShopCertification::getDeleted, 0)
            );
            if (sysBizShopCertifications != null && !sysBizUser.getTenantId().equals(sysBizShopCertifications.getTenantId())) {
                return AjaxResult.error("该用户已认证，选择站点和认证站点不匹配");
            }
        }else{
            sysBizUser.setTenantId(null);
        }
        return toAjax(sysBizUserService.updateById(sysBizUser));
    }

    /**
     * 删除用户列
     */
    @PreAuthorize("@ss.hasPermi('shop:user:remove')")
    @Log(title = "用户列", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysBizUserService.deleteSysBizUserByIds(ids));
    }

    /**
     * 批量注册会员
     */
    @Log(title = "批量注册会员", businessType = BusinessType.IMPORT)
    @PostMapping("/registerImportData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysBizUser> util = new ExcelUtil<SysBizUser>(SysBizUser.class);
        List<SysBizUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = getLoginUser();
        String operName = loginUser.getUsername();
        int message = sysBizUserService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 批量注册会员 模板
     */
    @PostMapping("/registerTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysBizUserRegister> util = new ExcelUtil<>(SysBizUserRegister.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 批量充值金额
     */
    @Log(title = "批量充值金额", businessType = BusinessType.IMPORT)
    @PostMapping("/rechargeImportData")
    public AjaxResult rechargeImportData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysBizUser> util = new ExcelUtil<SysBizUser>(SysBizUser.class);
        List<SysBizUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = getLoginUser();
        String operName = loginUser.getUsername();
        int message = sysBizUserService.registerImportData(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 批量充值金额 模板
     */
    @PostMapping("/rechargeTemplate")
    public void rechargeTemplate(HttpServletResponse response) {
        ExcelUtil<SysBizUserRecharge> util = new ExcelUtil<>(SysBizUserRecharge.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 修改上级
     */
    @PutMapping("/setSuperior")
    public AjaxResult setSuperior(@RequestBody SubordinateDto subordinateDto) {
        SysBizUser sysBizUser = sysBizUserService.getOne(new LambdaQueryWrapper<SysBizUser>()
                .eq(SysBizUser::getUserPhone, subordinateDto.getPhone())
                .eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
        if (sysBizUser == null || sysBizUser.getDeleted().equals(OrderDeleteEnum.DELETE.getKey())) {
            return error("用户不存在");
        }
        if (sysBizUser.getUserRole() == 0) {
            return error("用户不是会员");
        }
        if (sysBizUser.getIsRegisterMember() == 1 && sysBizUser.getProcessStatus() == 1) {
            return error("用户注册会员信息未审核，请先审核");
        }
        if (sysBizUser.getIsRegisterMember() == 1 && sysBizUser.getProcessStatus() == 3) {
            return error("用户注册会员信息审核未通过");
        }
        if (sysBizUser.getId().equals(subordinateDto.getId())) {
            return error("不能设置自己");
        }
        SysBizUser user = sysBizUserService.getById(subordinateDto.getId());
        List<Long> list = sysBizUserService.findBySubordinate(user);
        if (!CollectionUtils.isEmpty(list) && list.contains(sysBizUser.getId())) {
            return error("该用户为当前修改用户的下级，不能修改为当前修改用户的上级");
        }
        user.setParentId(sysBizUser.getId());
        user.setVerifyStatus(1);
        user.setVerifyTime(DateUtils.getNowDate());
        sysBizUserService.updateById(user);
        return success();
    }

    /**
     * 新增下级
     */
    @PutMapping("/setSubordinate")
    public AjaxResult setSubordinate(@RequestBody SubordinateDto subordinateDto) {
        SysBizUser sysBizUser = sysBizUserService.getOne(new LambdaQueryWrapper<SysBizUser>()
                .eq(SysBizUser::getUserPhone, subordinateDto.getPhone())
                .eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
        if (sysBizUser == null || sysBizUser.getDeleted().equals(OrderDeleteEnum.DELETE.getKey())) {
            return error("用户不存在");
        }
        if (sysBizUser.getUserRole() == 0) {
            return error("用户不是会员");
        }
        if (sysBizUser.getIsRegisterMember() == 1 && sysBizUser.getProcessStatus() == 1) {
            return error("用户注册会员信息未审核，请先审核");
        }
        if (sysBizUser.getIsRegisterMember() == 1 && sysBizUser.getProcessStatus() == 3) {
            return error("用户注册会员信息审核未通过");
        }
        if (sysBizUser.getId().equals(subordinateDto.getId())) {
            return error("不能设置自己");
        }
        SysBizUser user = sysBizUserService.getById(subordinateDto.getId());
        List<Long> list = sysBizUserService.findBySuperior(user);
        if (list.contains(sysBizUser.getId())) {
            return error("该用户为当前修改用户的上级，不能修改为当前修改用户的下级");
        }
        sysBizUser.setParentId(user.getId());
        sysBizUser.setVerifyStatus(1);
        sysBizUser.setVerifyTime(DateUtils.getNowDate());
        sysBizUserService.updateById(sysBizUser);
        return success();
    }





    /**
     * 对接老系统用户和用户地址
     */
    @RequestMapping("/getOldAddress")
    public AjaxResult getOldAddress() {
        String userAddress = HttpUtils.sendGet(userAddressUrl);

        // 解析响应
        JSONObject jsonResponse = JSON.parseObject(userAddress);
        int code = jsonResponse.getIntValue("code");

        if(code!=200){
            return AjaxResult.warn("用户和地址同步失败");
        }

        String jsonArrayString = jsonResponse.getString("data");
        List<ExternalUserDto> externalCouponDtoList = JSON.parseArray(jsonArrayString, ExternalUserDto.class);
        for (ExternalUserDto externalUserDto : externalCouponDtoList) {

            String name = externalUserDto.getName();
            String phone = externalUserDto.getPhone();

            if(StringUtils.isBlank(phone)){
                continue;
            }

            SysBizUser bizUser = sysBizUserService.getOne(new LambdaQueryWrapper<SysBizUser>()
                    .eq(SysBizUser::getUserPhone, phone)
                    .eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));

            if(bizUser != null){
               continue;
            }
            SysBizUser sysBizUser = new SysBizUser();
            sysBizUser.setUserPhone(phone);
            sysBizUser.setPassword(SecurityUtils.encryptPassword(phone));
            sysBizUser.setNickName(StringUtils.isBlank(name)?"禾饴"+ RandomStringUtils.randomAlphabetic(8):name);
            sysBizUser.setIsRegisterMember(0);
            sysBizUser.setDisplayed(BizUserStatusEnum.OK.getKey());
            sysBizUser.setCreateTime(DateUtils.getNowDate());
            sysBizUser.setTenantId(2L);
            sysBizUser.setScore(0L);
            sysBizUser.setGrade(0L);
            sysBizUser.setIsAdmin(0);
            sysBizUser.setUserRole(1);
            sysBizUser.setUpdateTime(new Date());
            sysBizUser.setDeleted(0);
            sysBizUser.setUseScore(0L);
            sysBizUser.setFrozenScore(0L);
            String token = TokenUtils.createToken();
            sysBizUser.setToken(token);
            sysBizUser.setProcessStatus(ProcessStatusEnum.UN_PROCESS.getKey());
            sysBizUser.setAuthenticationStatus(0);
            sysBizUserService.save(sysBizUser);

            if(!CollectionUtils.isEmpty(externalUserDto.getAddresses())){
                List<SysBizUserAddress> sysBizUserAddresses = new ArrayList<>();
                for (ExternalAddressDto externalAddressDto : externalUserDto.getAddresses()) {
                    SysBizUserAddress sysBizAddress = new SysBizUserAddress();
                    sysBizAddress.setTenantId(sysBizUser.getTenantId());
                    sysBizAddress.setUserId(sysBizUser.getId());
                    sysBizAddress.setPhone(StringUtils.isBlank(externalAddressDto.getTel())?sysBizUser.getUserPhone():externalAddressDto.getTel());
                    sysBizAddress.setProvince("江苏省"); //省
                    sysBizAddress.setCity("无锡市"); //市
                    if(StringUtils.isBlank(externalAddressDto.getZipCode())){
                        sysBizAddress.setArea("");  //区
                    }else{
                        sysBizAddress.setArea(externalAddressDto.getZipCode().substring(externalAddressDto.getZipCode().indexOf("无锡市") + 3));
                    }
                    sysBizAddress.setName(externalAddressDto.getName());
                    sysBizAddress.setDetails(externalAddressDto.getZipCode()+externalAddressDto.getProvinceCn()+externalAddressDto.getUserAddress());
                    sysBizAddress.setStatus(0);
                    sysBizAddress.setCreateTime(DateUtils.getNowDate());
                    sysBizAddress.setUpdateTime(DateUtils.getNowDate());
                    sysBizAddress.setStreet(externalAddressDto.getProvinceCn());
                    sysBizAddress.setHouseNum(externalAddressDto.getUserAddress());
                    sysBizAddress.setProvinceCode(externalAddressDto.getProvince());
                    sysBizAddress.setCityCode(externalAddressDto.getCity());
                    sysBizAddress.setAreaCode(externalAddressDto.getArea());
                    sysBizAddress.setLineName(externalAddressDto.getLineName());
//                    sysBizAddress.setStreetCode();  // 街道编号
                    sysBizUserAddresses.add(sysBizAddress);
                }
                sysBizUserAddressService.saveBatch(sysBizUserAddresses);
            }
        }

        return AjaxResult.success();
    }
}
